package com.cat.model.web.action.admin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alonew.core.commons.page.Page;
import com.alonew.json.JSONArray;
import com.alonew.json.JSONException;
import com.alonew.json.JSONObject;
import com.cat.model.biz.logic.BasLogic;
import com.cat.model.biz.service.admin.ModelInfoService;
import com.cat.model.common.model.common.BasConfigVO;
import com.cat.model.common.model.common.CompanyInfoVO;
import com.cat.model.common.model.common.ModelExperVO;
import com.cat.model.common.model.common.ModelInfoVO;
import com.cat.model.common.model.common.ModelStyleVO;
import com.cat.model.common.model.common.PlmCityVO;
import com.cat.model.common.model.common.PlmCountryVO;
import com.cat.model.common.model.common.PlmProvinceVO;
import com.cat.model.common.util.Constant;
import com.cat.model.common.util.ErrorCode;
import com.cat.model.common.util.ImageUtil;
import com.cat.model.dao.common.PlmCommDAO;
import com.cat.model.dao.mapper.ModelMapper;
import com.cat.model.web.action.base.AdminAction;

public class ModelInfoManagerAction extends AdminAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 425636316597986569L;

	private ModelInfoVO modelInfo;
	private Long id;
	private File coverImage;
	private String coverImageFileName; 
	private String coverImageUrl;
	private String countryCode; 
	private String provinceCode; 
	
	private String name;
	private Long companyId;
	private BigDecimal price;
	private String modelCode;
	@Autowired
	private ModelInfoService modelInfoService; 
	
	@Autowired
	private PlmCommDAO plmCommDAO;
	
	@Autowired
	private ModelMapper modelMapper;
	
	@Autowired
	private BasLogic basLogic; 
	
	/**
	 * list
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String list() {
		Map<String, Object> condition = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(name)){
			condition.put("name", name);
		}
		if(StringUtils.isNotBlank(modelCode)){
			condition.put("modelCode", modelCode);
		}
		if(price!=null){
			condition.put("price", price);
		}
		if(companyId!=null){
			condition.put("companyId", companyId);
		}
		
		Page page = this.fetchPageParams();
		page.setNumPerPage(20);
		
		Long totalCount = plmCommDAO.searchSize("manager.searchModelInfoSize", condition);
		page.setTotalCount(totalCount);
		int start = (page.getPageNum() -1) * page.getNumPerPage();
		if(start < 0){
			start = 0;
		}
		
		List<ModelInfoVO> list = (List<ModelInfoVO>)plmCommDAO.search("manager.searchModelInfo", condition, start, page.getNumPerPage());
		for (ModelInfoVO modelInfoVO : list) {
			CompanyInfoVO companyInfoVO=modelMapper.getCompanyInfo(modelInfoVO.getCompanyId());
			if(companyInfoVO!=null){
				modelInfoVO.setCompanyName(companyInfoVO.getName());
			}
			modelInfoVO.setCoverImage(ImageUtil.wrapImageUrl(modelInfoVO.getCoverImage()));
		}
		List<CompanyInfoVO> companyList = modelMapper.getAllCompany();
		request.setAttribute("companyList", companyList);
		request.setAttribute("name", name);
		request.setAttribute("price", price);
		request.setAttribute("modelCode", modelCode);
		request.setAttribute("companyId", companyId);
		request.setAttribute("list", list);
		request.setAttribute("size", totalCount);
		return "list";
	}
	
	public String deleteSingle() {
		modelInfoService.deleteModelInfo(id);
		okAlert("删除成功！");
		return "list";
	}
	
	public String toAdd(){
		List<BasConfigVO> styleList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_STYLE_CODE);
		List<BasConfigVO> experList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_EXPER_CODE);
		List<BasConfigVO> hairColorList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_HAIRCOLOR_CODE);
		List<BasConfigVO> raceList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_RACE_CODE);
		List<BasConfigVO> eyeList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_EYE_CODE);
		List<BasConfigVO> skinColorList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_SKINCOLOR_CODE);
		List<BasConfigVO> ageGroupList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_AGE_GROUP);
		List<CompanyInfoVO> companyList = modelMapper.getAllCompany();
		request.setAttribute("styleList", styleList);
		request.setAttribute("experList", experList);
		request.setAttribute("companyList", companyList);
		request.setAttribute("hairColorList", hairColorList);
		request.setAttribute("raceList", raceList);
		request.setAttribute("eyeList", eyeList);
		request.setAttribute("skinColorList", skinColorList);
		request.setAttribute("ageGroupList", ageGroupList);
		List<PlmCountryVO> countryList = plmCommDAO.getPlmCountry();
		request.setAttribute("countryList", countryList);
		if(countryList!=null){
			List<PlmProvinceVO> provinceList = plmCommDAO.getPlmProvince(countryList.get(0).getCode());
			request.setAttribute("provinceList", provinceList);
		}
		return "add";
	}
	
	public String add(){
		try {
			if(coverImage != null){
				BufferedImage img = ImageIO.read(new FileInputStream(coverImage));
				if(img == null){
					this.printHTML("<script>parent.callback(" + false + ", '"+"图片格式不正确"+"')</script>");
					return "list";
				}
			}
			
			/*ModelInfoVO qryModelInfo = modelMapper.getModelInfoByCode(modelInfo.getModelCode());
			if(qryModelInfo!=null){
				this.printHTML("<script>parent.callback(" + false + ", '"+"模特编号["+modelInfo.getModelCode()+"]已存在"+"')</script>");
				return "list";
			}*/
			
			String[] style = request.getParameterValues("style"); 
			String[] exper = request.getParameterValues("exper"); 
			modelInfoService.createModelInfo(modelInfo,style,exper, coverImage, coverImageFileName);
		} catch (Exception e) {
			e.printStackTrace();
			parentAlert(false, e.getMessage());
			return "list";
		}
		
		parentAlert(true, "保存成功");
		return "list";
	}
	
	public String toEdit(){
		modelInfo = modelMapper.getModelInfo(id);
		List<BasConfigVO> styleList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_STYLE_CODE);
		List<BasConfigVO> experList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_EXPER_CODE);
		List<CompanyInfoVO> companyList = modelMapper.getAllCompany();
		List<BasConfigVO> hairColorList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_HAIRCOLOR_CODE);
		List<BasConfigVO> raceList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_RACE_CODE);
		List<BasConfigVO> eyeList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_EYE_CODE);
		List<BasConfigVO> skinColorList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_SKINCOLOR_CODE);
		List<BasConfigVO> ageGroupList = basLogic.getBasConfigByName(Constant.CONFIG_NAME_AGE_GROUP);
		request.setAttribute("styleList", styleList);
		request.setAttribute("experList", experList);
		request.setAttribute("companyList", companyList);
		request.setAttribute("hairColorList", hairColorList);
		request.setAttribute("raceList", raceList);
		request.setAttribute("eyeList", eyeList);
		request.setAttribute("skinColorList", skinColorList);
		request.setAttribute("ageGroupList", ageGroupList);
		List<ModelStyleVO> styles = modelMapper.getModelStyleList(id);
		Map<String, Object> styleMap = new HashMap<String, Object>();
		if(styles!=null&&styles.size()>0){
			for (int i = 0; i < styles.size(); i++) {   
				ModelStyleVO styleVO = (ModelStyleVO)styles.get(i);
				styleMap.put(styleVO.getStyleCode(), styleVO.getStyleCode().toString());
			}
		}
		request.setAttribute("styleMap",styleMap);
		
		List<ModelExperVO> expers = modelMapper.getModelExperList(id);
		Map<String, Object> experMap = new HashMap<String, Object>();
		if(expers!=null&&expers.size()>0){
			for (int i = 0; i < expers.size(); i++) {   
				ModelExperVO experVO = (ModelExperVO)expers.get(i);
				experMap.put(experVO.getExperCode(), experVO.getExperCode().toString());
			}
		}
		request.setAttribute("experMap",experMap);
		
		if(modelInfo != null){
			coverImageUrl = ImageUtil.wrapImageUrl(modelInfo.getCoverImage());
		}
		
		List<PlmCountryVO> countryList = plmCommDAO.getPlmCountry();
		request.setAttribute("countryList", countryList);
		if(modelInfo.getCountryCode()!=null){
			List<PlmProvinceVO> provinceList = plmCommDAO.getPlmProvince(modelInfo.getCountryCode());
			request.setAttribute("provinceList", provinceList);
		}
		
		if(modelInfo.getProvinceCode()!=null){
			List<PlmCityVO> cityList = plmCommDAO.getPlmCity(modelInfo.getProvinceCode());
			request.setAttribute("cityList", cityList);
		}
		
		return "edit";
	}
	
	public String edit(){
		try {
			if(coverImage != null){
				BufferedImage img = ImageIO.read(new FileInputStream(coverImage));
				if(img == null){
					this.printHTML("<script>parent.callback(" + false + ", '"+"图片格式不正确"+"')</script>");
					return "list";
				}
			}
			ModelInfoVO qryModelInfo = modelMapper.getModelInfoByCode(modelInfo.getModelCode());
			if(qryModelInfo!=null&&!qryModelInfo.getId().equals(modelInfo.getId())){
				this.printHTML("<script>parent.callback(" + false + ", '"+"模特编号["+modelInfo.getModelCode()+"]已存在"+"')</script>");
				return "list";
			}
			
			String[] style = request.getParameterValues("style"); 
			String[] exper = request.getParameterValues("exper"); 
			if(modelInfo.getCountryCode().contains(",")){
				String[] strs = modelInfo.getCountryCode().split(",");
				modelInfo.setCountryCode(strs[0]);
			}
			if(modelInfo.getProvinceCode()!=null&&modelInfo.getProvinceCode().contains(",")){
				String[] strs = modelInfo.getProvinceCode().split(",");
				modelInfo.setProvinceCode(strs[0]);
			}
			if(modelInfo.getCityCode()!=null&&modelInfo.getCityCode().contains(",")){
				String[] strs = modelInfo.getCityCode().split(",");
				modelInfo.setCityCode(strs[0]);
			}
			
			modelInfoService.updateModelInfo(modelInfo,style,exper, coverImage, coverImageFileName);
		} catch (Exception e) {
			e.printStackTrace();
			parentAlert(false, e.getMessage());
			return "list";
		}
			
		parentAlert(true, "保存成功");
		return "list";
	}
	
	public void getProvince(){
		List<PlmProvinceVO> provinceList = plmCommDAO.getPlmProvince(countryCode);
		
		JSONObject resultJson = ErrorCode.OK.responseJSON();
		try {
			JSONObject json = new JSONObject();
			JSONArray menuArray = new JSONArray();
			if(provinceList != null && provinceList.size() > 0){
				for(PlmProvinceVO bean : provinceList){				
					JSONObject detailJson = new JSONObject();
					detailJson.put("code", bean.getCode());
					detailJson.put("name", bean.getName());
					
					menuArray.put(detailJson);
				}
			}
			
			json.put("provinceList", menuArray);
			resultJson.put("data", json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		print(resultJson.toString());
	}
	
	public void getCity(){
		List<PlmCityVO> cityList = plmCommDAO.getPlmCity(provinceCode);
		
		JSONObject resultJson = ErrorCode.OK.responseJSON();
		try {
			JSONObject json = new JSONObject();
			JSONArray menuArray = new JSONArray();
			if(cityList != null && cityList.size() > 0){
				for(PlmCityVO bean : cityList){				
					JSONObject detailJson = new JSONObject();
					detailJson.put("code", bean.getCode());
					detailJson.put("name", bean.getName());
					
					menuArray.put(detailJson);
				}
			}
			
			json.put("cityList", menuArray);
			resultJson.put("data", json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		print(resultJson.toString());
	}


	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public ModelInfoVO getModelInfo() {
		return modelInfo;
	}

	public void setModelInfo(ModelInfoVO modelInfo) {
		this.modelInfo = modelInfo;
	}

	public File getCoverImage() {
		return coverImage;
	}

	public void setCoverImage(File coverImage) {
		this.coverImage = coverImage;
	}

	public String getCoverImageFileName() {
		return coverImageFileName;
	}

	public void setCoverImageFileName(String coverImageFileName) {
		this.coverImageFileName = coverImageFileName;
	}

	public String getCoverImageUrl() {
		return coverImageUrl;
	}

	public void setCoverImageUrl(String coverImageUrl) {
		this.coverImageUrl = coverImageUrl;
	}

	public String getCountryCode() {
		return countryCode;
	}

	public void setCountryCode(String countryCode) {
		this.countryCode = countryCode;
	}

	public String getProvinceCode() {
		return provinceCode;
	}

	public void setProvinceCode(String provinceCode) {
		this.provinceCode = provinceCode;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getCompanyId() {
		return companyId;
	}

	public void setCompanyId(Long companyId) {
		this.companyId = companyId;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public String getModelCode() {
		return modelCode;
	}

	public void setModelCode(String modelCode) {
		this.modelCode = modelCode;
	}
	
}
